import functools
import json
from xml.dom import UserDataHandler

from flask import (
	Blueprint, flash, g, redirect, render_template, request, session, url_for,Response,abort,jsonify
)
from werkzeug.security import check_password_hash, generate_password_hash

from flaskr.db import get_db

from flask_cors import *

bp = Blueprint('vaccine', __name__, url_prefix='/')

cors=CORS(bp,supports_credentials=True)

@bp.route('/vaccine',methods=['GET','POST'])
def vaccine():
	if(session.get('permission') != 'User'):
		abort(403)
	db = get_db()

	if request.method == 'GET':
		#vaccine record for user
		username = session.get('id')
		test_records = db.execute(
			'SELECT time,status,medical_point_id FROM Vaccine_record WHERE user_id = ?', (username,)
		).fetchall()
		record_list = []
		for record in test_records:
			record_list.append({'medical_point_id':record['medical_point_id'],'time':record['time'],'result':record['status']})
		return jsonify({'record_list':record_list})

	if request.method == 'POST':
		#post application for vaccine
		data = request.get_data()
		data = json.loads(data.decode("utf-8"))
		username = data['username']
		try:
			#not same with nucleic
			#not session.get('id')
			#but data['medical_point_id']
			db.execute(
				'UPDATE Medical_point set vaccine = vaccine -1 where id = ?',
	   			(data['medical_point_id']),
			)
			db.execute(
				'INSERT INTO Vaccine_record (user_id,medical_point_id,status,manufacturer) VALUES (?, ?, ?, ?)',
	   			(session.get('id'), data['medical_point_id'], 1, data['manufactor']),
			)
			db.commit()
		except db.IntegrityError:
			abort(500)
		finally:
			return "success"
	abort(405)  #method not allowed


@bp.route('/vaccine_record',methods=['GET','POST'])
def vaccine_record():

	if(session.get('permission') != 'Medical_point'):
		abort(403)
	db = get_db()
	if request.method == 'GET':
		# return the unfinished records
		test_records = db.execute(
			'SELECT username,time,Vaccine_record.status FROM Vaccine_record join User WHERE medical_point_id = ? and Vaccine_record.status = 1 and user_id = User.id', 
			(session.get('id'),)
		).fetchall()
		record_list = []
		for record in test_records:
			record_list.append({'username':record['username'],'time':record['time'],'result':record['status']})
		return jsonify({'record_list':record_list})

	if request.method == 'POST':
		# update vaccine result
		data = request.get_data()    
		data = json.loads(data.decode("utf-8"))
		try:
			db.execute(
                "UPDATE Vaccine_record set status = ? where id = ?",
                (0,data['record-ID'],),
            )
			db.commit()
		except db.IntegrityError:
			abort(500)
		else:
			return "success"
